// pages/loginWX/loginWX.js
const config = require('../../config.js')
Page({
  data: {
    avatar: '',
    nickname: '',
    avatarURL: ''
  },
  onLoad(){
    // console.log(config.BASE_URL);
  },
  async onChooseAvatar(e) {
    console.log(e);
    this.setData({
      avatar: e.detail.avatarUrl
    })
  },
  onInputChange(e) {
    this.setData({
      nickname: e.detail.value
    })
  },
  getNickname(e) {
    console.log(e);
  },
  login() {
    const user = { name: this.data.nickname }
    const avatar = this.data.avatar
    wx.setStorageSync('user', {
      avatar: this.data.avatar,
      name: this.data.nickname
    })
    // 在小程序的页面JS中调用 wx.login()
    wx.login({
      success(res) {
        if (res.code) {
          // 发送code到后端，换取openid和session_key
          wx.request({
            url: `${config.BASE_URL}/user/login`,
            method: 'POST',
            header: {
              'Content-Type': 'application/json'
            },
            data: { code: res.code, name: user.name },
            success(res) {
              if (res.statusCode >= 400 ) return wx.showToast({
                title: '登录失败',
                icon: 'error'
              })
              wx.switchTab({
                url: '/pages/home/home',
              })
              console.log('后端返回的登录信息:', res.data?.data);
              wx.setStorageSync('token', res.data?.data?.token);
              wx.setStorageSync('userInfo', {
                id: res.data?.data?.id,
                openId: res.data?.data?.openid
              })

              wx.uploadFile({
                filePath: avatar,
                name: 'file',
                url: `${config.BASE_URL}/user/upload_avatar`,
                header: {
                  token: res.data?.data?.token
                },
                success (result) {
                  console.log(result);
                }
              })
            },
            fail(err) {
              console.error('登录失败:', err);
            }
          });
        } else {
          console.error('获取code失败:', res.errMsg);
        }
      },
      fail(err) {
        console.error('wx.login调用失败:', err);
      }
    });
  },
  
})